import { getProfile, login, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  profile: {
    id: '',
    name: '',
    avatar_image: '',
    last_login_time: '',
    description: ''
  },
  userPermissions: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_PROFILE: (state, profile) => {
    state.profile = {
      id: profile.id ?? 0,
      name: profile.name ?? '',
      avatar_image: profile.avatar_image.length > 0 ? profile.avatar_image[0].url : '/static/img/default_user.png',
      last_login_time: profile.last_login_time ?? '',
      description: profile.description ?? ''
    }
  },
  SET_USERPERMISSIONS: (state, permissions) => {
    state.userPermissions = permissions
  }
}

const actions = {
  // user login
  login({ commit, dispatch }, userInfo) {
    const { username, password, captcha_id, captcha_code } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password, captcha_code, captcha_id }).then(async response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user profile
  getProfile({ commit, state }) {
    return new Promise((resolve, reject) => {
      getProfile(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { permissions } = data

        // permissions must be a non-empty array
        if (!permissions || permissions.length <= 0) {
          reject('getProfile: permissions must be a non-null array!')
        }

        commit('SET_USERPERMISSIONS', permissions)
        commit('SET_PROFILE', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then((response) => {
        commit('SET_TOKEN', '')
        commit('SET_USERPERMISSIONS', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        dispatch('tagsView/delAllViews', null, { root: true })

        // 删除数据字典
        dispatch('dictionaryConfig/delConfig', null, { root: true })
        // 上传配置信息
        dispatch('fileUploadConfig/delConfig', null, { root: true })

        // 清空sessionStorage
        window.sessionStorage.clear()

        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_USERPERMISSIONS', [])
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
